<?php
namespace app\api\controller;
use app\api\common\Common;
use app\api\common\ApiErrDesc;

class Login extends Common{

	/**
	 * 微信授权步骤: 1.前端传code过来，2.后端获取openid、sessionkey, 3.保存用户信息。
	 * @return [json]     [返回授权结果及用户id]
	 */
  	public function wxlogin(){
		$data = $this->params;
		$wxurl = $this->wxOpenidUrl;
		$appid = $this->wxappid;
		$secret = $this->wxsecret;
		$url = $wxurl."appid=$appid&secret=$secret&js_code=".$data['code']."&grant_type=authorization_code";

		// 通过code换取网页授权access_token
        $weixin =  file_get_contents($url);
        $jsondecode = json_decode($weixin);   // 对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);// 转换成数组
        if(!isset($array['openid'])){
            $this->return_msg(ApiErrDesc::AUTHORFAIL[0], ApiErrDesc::AUTHORFAIL[1]);
            exit();
        } else {
			// 查看数据库中是否存在已授权的openid, 有只返回userid，无插入一条数据。
			$isExist = db('user')->where('openid = "'.$array['openid'].'"')->column('id');
			if($isExist){
				// 已经存在，则只需要返回userid即可
				$userinfo = db('user')->where('id='.intval($isExist[0]))->find();
				if(intval($userinfo['del']) == 1){
					$this->return_msg(ApiErrDesc::ACCOUNTDEL[0], ApiErrDesc::ACCOUNTDEL[1]);
				}
				$returnData['userid'] = $isExist[0];
        		$this->return_msg(ApiErrDesc::SUCCESS[0], ApiErrDesc::SUCCESS[1], $returnData);
			} else {
				// 不存在，则新增一条用户授权信息
				$data['source'] = 'wx';
				$data['addtime'] = time();
				$data['openid'] = $array['openid'];
				if(!isset($data['openid'])){
					$this->return_msg(ApiErrDesc::AUTHORAGAIN[0], ApiErrDesc::AUTHORAGAIN[1]);
				}
				$res = db('user')->insert($data);
				if($res){
					$arrayOpenid = db('user')->where('openid ="'.$data['openid'].'"')->column('id');
					$insertRes['userid'] = $arrayOpenid[0];
					$this->return_msg(ApiErrDesc::SUCCESS[0], ApiErrDesc::SUCCESS[1], $insertRes);
				} else {
					$this->return_msg(ApiErrDesc::AUTHORAGAIN[0], ApiErrDesc::AUTHORAGAIN[1]);
				}
			}
        }
	}
	
	// ============  普通账号相关操作  ==============
	/**
     * 普通账号用户注册
     * @return  [json]  [注册返回结果]
     */
    public function register(){
        $data = $this->params;
        $this->check_code($data['user_name'], $data['code']); // 检查验证码
        $user_name_type = $this->check_username($data['user_name']);
        switch ($user_name_type) {
            case 'phone':
                $this->check_exist($data['user_name'], 'phone', 0);
                $data['phone'] = $data['user_name'];
                break;
            case 'email':
                $this->check_exist($data['user_name'], 'email', 0);
                $data['email'] = $data['user_name'];
                break;
		}
		$data['pwd'] = $data['user_pwd'];
        // 将用户信息写入数据库
		unset($data['user_name']);
		unset($data['user_pwd']);
		unset($data['code']);
        $data['addtime'] = time();
        $res = db('user')->insert($data);
        if (!$res) {
            $this->retrun_msg(ApiErrDesc::REGISTFAIL[0], ApiErrDesc::REGISTFAIL[1]);
        } else {
            $this->return_msg(ApiErrDesc::SUCCESS[0], ApiErrDesc::SUCCESS[1]);
        }
	}
	

	/**
     * 普通账号用户登录
     * @return  [json]  [注册返回结果]
     */
    public function login(){
        $data = $this->params;
        $user_name_type = $this->check_username($data['user_name']); // 检测用户名
        switch ($user_name_type) {
            case 'phone':
                $this->check_exist($data['user_name'], 'phone', 1);
                $db_res = db('user')
                    ->field('id, name, phone, avator, email, pwd')
                    ->where('phone', $data['user_name'])
                    ->find();
                break;
            case 'email':
                $this->check_exist($data['user_name'], 'email', 1);
                $db_res = db('user')
                    ->field('id, name, phone, avator, email, pwd')
                    ->where('email', $data['user_name'])
                    ->find();
                break;
        }
        if ($db_res['pwd'] !== $data['user_pwd']) {
            $this->return_msg(ApiErrDesc::LOGINERR[0], ApiErrDesc::LOGINERR[1]);
        } else {
            unset($db_res['pwd']); // 密码永不返回
            $this->return_msg(ApiErrDesc::SUCCESS[0], ApiErrDesc::SUCCESS[1], $db_res);
        }
	}
	

	/**
     * 用户上传头像
     * @return  [json]  [注册返回结果]
     */
    public function upload_head_img() {
        $data = $this->params;
        // 上传文件,获得路径  注意：request()->file('avator') 中的avator字段为用户上传的头像字段
        $head_img_path = $this->upload_file(request()->file('avator'), 'avator', $data['user_id']);
        // 存入数据库
        $res = db('user')->where('id', $data['user_id'])->setField('avator', $head_img_path);
        if ($res) {
            $this->return_msg(ApiErrDesc::SUCCESS[0], ApiErrDesc::SUCCESS[1], $head_img_path);
        } else {
            $this->return_msg(ApiErrDesc::AVATORERR[0], ApiErrDesc::AVATORERR[1]);
        }
    }

    /**
     * 授权用户设置密码
     * @return [json]  [设置密码结果]
     */
    public function set_pwd(){
        $data = $this->params;
        echo "功能尚未开发，请稍等...";
    }


    /**
     * 用户修改密码
     * @return  [json]  [注册返回结果]
     */
    public function change_pwd() {
        $data = $this->params;
        // 检查用户名并取出数据库中的密码
        $user_name_type = $this->check_username($data['user_name']);
        switch ($user_name_type) {
            case 'phone':
                $this->check_exist($data['user_name'], 'phone', 1);
                $where['phone'] = $data['user_name'];
                break;
            case 'email':
                $this->check_exist($data['user_name'], 'email', 1);
                $where['email'] = $data['user_name'];
                break;
        }
        // 判断原始密码是否正确
        $db_ini_pwd = db('user')->where($where)->value('pwd');
        if ($db_ini_pwd !== $data['user_ini_pwd']) {
            $this->return_msg(ApiErrDesc::ORIGINFAIL[0], ApiErrDesc::ORIGINFAIL[1]);
        }
        // 把新的密码存入数据库
        $res = db('user')->where($where)->setField('pwd', $data['user_pwd']);
        if ($res !== false) {
            $this->return_msg(ApiErrDesc::SUCCESS[0], ApiErrDesc::SUCCESS[1]);
        } else {
            $this->return_msg(ApiErrDesc::PWDINSERTERR[0], ApiErrDesc::PWDINSERTERR[1]);
        }
    }

    /**
     * 用户找回密码
     * @return  [json]  [注册返回结果]
     */
    public function find_pwd() {
        $data = $this->params;
        $this->check_code($data['user_name'], $data['code']);
        $user_name_type = $this->check_username($data['user_name']);
        switch ($user_name_type) {
            case 'phone':
                $this->check_exist($data['user_name'], 'phone', 1);
                $where['phone'] = $data['user_name'];
                break;
            case 'email':
                $this->check_exist($data['user_name'], 'email', 1);
                $where['email'] = $data['user_name'];
                break;
        }
        // 修改数据库
        $res = db('user')->where($where)->setField('pwd', $data['user_pwd']);
        if ($res !== false) {
            $this->return_msg(ApiErrDesc::SUCCESS[0], ApiErrDesc::SUCCESS[1]);
        } else {
            $this->return_msg(ApiErrDesc::PWDINSERTERR[0], ApiErrDesc::PWDINSERTERR[1]);
        }
    }


    /**
     * 合成上面两个（手机和邮箱）接口
     * @return  [json]  [注册返回结果]
     */
    public function bind_username() {
        $data = $this->params;
        // 检测验证码
        $this->check_code($data['user_name'], $data['code']);
        // 判断用户名
        $user_name_type = $this->check_username($data['user_name']);
        switch ($user_name_type) {
        case 'phone':
            $type_text                 = '手机号';
            $update_data['phone'] = $data['user_name'];
            break;
        case 'email':
            $type_text                 = '邮箱';
            $update_data['email'] = $data['user_name'];
            break;
        }
        // 修改数据库
        $res = db('user')->where('id', $data['user_id'])->update($update_data);
        if ($res !== false) {
            $this->return_msg(ApiErrDesc::SUCCESS[0], $type_text . '绑定成功!');
        } else {
            $this->return_msg(ApiErrDesc::BINDERROR[0], $type_text . ApiErrDesc::BINDERROR[1]);
        }
    }

     /**
     * 设置用户昵称
     * @return  [json]  [注册返回结果]
     */
    public function set_nickname() {
        $data = $this->params;
        // 检测昵称
        $res = db('user')->where('name', $data['user_nickname'])->find();
        if ($res) {
            $this->return_msg(ApiErrDesc::NAMEEXIST[0], ApiErrDesc::NAMEEXIST[1]);
        }
        // 写入数据库
        $res = db('user')->where('id', $data['user_id'])->setField('name', $data['user_nickname']);
        if (!$res) {
            $this->return_msg(ApiErrDesc::NAMEINSERTER[0], ApiErrDesc::NAMEINSERTER[1]);
        }else{
            $this->return_msg(ApiErrDesc::SUCCESS[0], ApiErrDesc::SUCCESS[1]);
        }
    }
}